const file = "https://soptest.7sef.com/api/sop/sop/file/upload"; //小程序文件服务器地址
// const api = 'http://10.2.3.36:9903/' //接口请求地址
const api = "https://soptest.7sef.com/api/"; //接口请求地址
const GET = (ops: any) => {
  let token = uni.getStorageSync("token");
  uni.request({
    url: api + ops.url,
    data: ops.data || {},
    header: {
      "Access-Token": token,
      "Content-Type": "application/json",
    },
    method: "GET",
    success: function (res: any) {
      if (res.data.code == 401) {
        uni.clearStorageSync();
        uni.navigateTo({ url: "/pages/login/index" });
        return;
      }
      if (res.statusCode == 500) {
        uni.showToast({
          title: res.msg || "服务器异常",
          icon: "none",
          duration: 5000,
        });
        ops.fail && ops.fail(res);
      }
      if (res.statusCode == 200 && res?.data?.code != 200) {
        uni.showToast({
          title: res?.data?.msg || "服务器异常",
          icon: "none",
          duration: 5000,
        });
      }
      if (ops.success) {
        ops.success(res.data);
        return;
      }
    },
    fail: function (res) {
      if (ops.fail) {
        ops.fail(res);
        return;
      }
    },
  });
};
const POST = (ops: any) => {
  let token = uni.getStorageSync("token") || "";
  uni.request({
    url: api + ops.url,
    data: ops.data || {},
    header: {
      "Access-Token": token,
      "Content-Type": ops.isJson
        ? "application/json"
        : "application/x-www-form-urlencoded",
    },
    method: "POST",
    success: function (res: any) {
      if (res.statusCode == 200) {
        ops.success && ops.success(res.data);
        if(res?.data.msg==="token已过期"){
          uni.clearStorageSync();
          uni.navigateTo({ url: "/pages/login/index" });
          return
        }
        if (res.data.code != 200) {
          uni.showToast({
            title: res?.data?.msg || "服务器异常",
            icon: "none",
            duration: 5000,
          });
        }
      } else if (res.statusCode == 401) {
        uni.clearStorageSync();
        uni.navigateTo({ url: "/pages/login/index" });
        return;
      } else {
        uni.showToast({
          title: res?.data?.msg || "服务器异常",
          icon: "none",
          duration: 5000,
        });
      }
      ops.complete && ops.complete(res);
    },
    fail: function (res) {
      if (ops.fail) {
        ops.fail(res);
        return;
      }
    },
  });
};
// 文件上传
const UPLOAD = (ops: any) => {
  console.log(ops,'ops');
  
  let token = uni.getStorageSync("token");
  uni.uploadFile({
    url: `${file}`,
    filePath: ops.data,
    // 支付宝必填
    fileType: "image",
    header: {
      "Access-Token": token,
    },
    name: "file",
    success: ops.success,
    fail: ops?.fail,
  });
};

export default {
  GET: GET,
  POST: POST,
  UPLOAD: UPLOAD,
};
